<template>
  <div>
    <el-dialog
      title="配置指标"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="800px"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        class="rule-form"
        label-width="120px"
        :disabled="!canEdit"
        v-loading="loading"
      >
        <el-form-item label="所属元指标" prop="metaIndexName">
          <el-input
            type="text"
            v-model="form.metaIndexName"
            readonly
            placeholder="请选择所属元指标"
            :disabled="!!row"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleOpenMetaIndexList"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="指标名称" prop="indexConfigName">
          <el-input
            type="text"
            v-model="form.indexConfigName"
            placeholder="请输入指标名称"
          ></el-input>
        </el-form-item>
        <!-- 如果选择的指标类型为设备参数类，不展示 -->
        <el-form-item
          v-if="form.indexType != 'ED'"
          label="时间维度"
          prop="timeDimension"
        >
          <el-input
            type="text"
            :value="
              form.timeDimension ? timeDimensionDictMap[form.timeDimension] : ''
            "
            disabled
            placeholder="请输入指标名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="指标编码" prop="indexConfigCode">
          <el-input
            type="text"
            v-model="form.indexConfigCode"
            disabled
            placeholder="请输入指标编码"
          ></el-input>
        </el-form-item>
        <!-- 如果选择的指标类型为设备参数类，不展示 -->
        <el-form-item
          v-if="form.indexType != 'ED'"
          label="组织维度"
          prop="bizOrgDimension"
        >
          <el-input
            type="text"
            :value="
              form.bizOrgDimension
                ? bizOrgDimensionDictMap[form.bizOrgDimension]
                : ''
            "
            disabled
            placeholder="请输入指标名称"
          ></el-input>
        </el-form-item>
        <!-- 有组织维度的，才显示具体组织 -->
        <el-form-item label="具体组织" prop="factoryDeptId" class="full-width">
          <div class="organization">
            <el-select
              v-model="form.factoryDeptId"
              placeholder="请选择工厂"
              :disabled="!!row"
              @change="handleFactoryDeptIdChange"
            >
              <el-option
                v-for="item in factoryDeptOptions"
                :key="item.factoryDeptId"
                :label="item.factoryName"
                :value="item.factoryDeptId"
              >
              </el-option>
            </el-select>
            <el-select
              v-if="['WS', 'LN'].includes(form.bizOrgDimension)"
              v-model="form.workshopId"
              placeholder="请选择车间"
              :disabled="!!row"
              @change="handleWorkshopIdChange"
            >
              <el-option
                v-for="item in workshopOptions"
                :key="item.workshopId"
                :label="item.workshopName"
                :value="item.workshopId"
              >
              </el-option>
            </el-select>
            <el-select
              v-if="['LN'].includes(form.bizOrgDimension)"
              v-model="form.lineId"
              placeholder="请选择产线"
              :disabled="!!row"
              @change="clearFormByOrg"
            >
              <el-option
                v-for="item in lineOptions"
                :key="item.lineId"
                :label="item.lineName"
                :value="item.lineId"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="设备分类" prop="equipSortCode">
          <el-select
            v-model="form.equipSortCode"
            placeholder="请选择设备分类"
            disabled
          >
            <el-option
              v-for="item in dict.equipSortcode"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="所属设备"
          prop="equipName"
          :rules="
            form.equipSortCode
              ? [
                  {
                    required: true,
                    message: '请选择所属设备',
                    trigger: 'change',
                  },
                ]
              : []
          "
        >
          <el-input
            type="text"
            v-model="form.equipName"
            readonly
            :disabled="!!row"
            placeholder="请选择所属设备"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleOpenEquipList"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="关联元指标" prop="defRelaDtosName">
          <el-input
            type="text"
            v-model="form.defRelaDtosName"
            disabled
            placeholder="请选择关联元指标"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="关联指标" prop="configRelaName">
          <el-input
            type="text"
            v-model="form.configRelaName"
            readonly
            placeholder="请选择关联指标"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleOpenIndexList"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="指标粒度" prop="indexGranularity">
          <el-select
            v-model="form.indexGranularity"
            disabled
            placeholder="请选择指标粒度"
          >
            <el-option
              v-for="item in dict.indexGranularity"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指标类型" prop="indexType">
          <el-select
            v-model="form.indexType"
            disabled
            placeholder="请选择指标类型"
          >
            <el-option
              v-for="item in dict.indexType"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 如果选择的指标类型是设备参数类，该字段不显示 -->
        <el-form-item
          v-if="form.indexType != 'ED'"
          label="指标一级分类"
          prop="indexSubTypeOne"
        >
          <el-select
            v-model="form.indexSubTypeOne"
            disabled
            placeholder="请选择指标一级分类"
          >
            <el-option
              v-for="item in dict.indexSubTypeOne_PD"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 如果选择的指标一级分类非能耗，该字段不显示(即能耗显示) -->
        <el-form-item
          v-if="form.indexSubTypeOne == 'ECM'"
          label="指标二级分类"
          prop="indexSubTypeTwo"
        >
          <el-select
            v-model="form.indexSubTypeTwo"
            disabled
            placeholder="请选择指标二级分类"
          >
            <el-option
              v-for="item in dict.indexSubTypeTwo_EC"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品控关注" prop="qulityControl">
          <el-select
            v-model="form.qulityControl"
            disabled
            placeholder="请选择品控关注"
          >
            <el-option
              v-for="item in dict.sys_yes_no"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指标单位" prop="indexUnit">
          <el-select
            v-model="form.indexUnit"
            disabled
            placeholder="请选择指标单位"
          >
            <el-option
              v-for="item in indexUnitOption"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="元指标描述" prop="remark" class="full-width">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入元指标描述"
          ></el-input>
        </el-form-item>

        <el-divider></el-divider>

        <el-form-item
          label="指标数据来源"
          prop="indexDataSource"
          label-width="160px"
        >
          <el-select
            v-model="form.indexDataSource"
            placeholder="请选择指标数据来源"
          >
            <el-option
              v-for="item in dict.indexDataSource"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-divider></el-divider>

        <!-- 指标数据来源为SYS_CAL时，显示 -->
        <el-form-item
          v-if="['SYS_CAL'].includes(form.indexDataSource)"
          label="系统统计实现类"
          prop="sysCalculator"
          label-width="160px"
          class="full-width"
        >
          <el-input
            type="text"
            v-model="form.sysCalculator"
            placeholder="请输入系统统计实现类"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="['EXPR'].includes(form.indexDataSource)"
          label="指标计算公式"
          prop="expression"
          label-width="160px"
          class="full-width"
        >
          <el-input
            type="textarea"
            v-model="form.expression"
            placeholder="请输入指标计算公式"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="['SYS_CAL', 'EXPR'].includes(form.indexDataSource)"
          label="系统计算间隔"
          prop="calInterval"
          label-width="160px"
        >
          <el-input-number v-model="form.calInterval"></el-input-number>
        </el-form-item>
        <el-form-item
          v-if="['SYS_CAL', 'EXPR'].includes(form.indexDataSource)"
          label="系统计算间隔时间单位"
          prop="calIntervalUnit"
          label-width="160px"
        >
          <el-select
            v-model="form.calIntervalUnit"
            placeholder="请选择系统计算间隔时间单位"
          >
            <el-option
              v-for="item in dict.timeUnit"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="['SYS_CAL', 'EXPR'].includes(form.indexDataSource)"
          label="计算范围"
          prop="rangePerCal"
          label-width="160px"
        >
          <el-input-number v-model="form.rangePerCal"></el-input-number>
        </el-form-item>
        <el-form-item
          v-if="['SYS_CAL', 'EXPR'].includes(form.indexDataSource)"
          label="最近一次计算时间"
          prop="latestCalTime"
          label-width="160px"
        >
          <el-date-picker
            v-model="form.latestCalTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          v-if="['SCADA'].includes(form.indexDataSource)"
          label="SCADA点位编码"
          prop="scadaPointCode"
          label-width="160px"
        >
          <el-input
            type="text"
            v-model="form.scadaPointCode"
            placeholder="请输入SCADA点位编码"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="canEdit"
          type="primary"
          :loading="saveloading"
          @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 元指标列表 -->
    <MetaIndexList
      :visible.sync="indexMetaListDialog.visible"
      :defaultValues="indexMetaListDialog.defaultValues"
      :selectableCallBack="metaSelectableCallBack"
      :multiple="false"
      @closeDialog="handleMetaIndexListClose"
    ></MetaIndexList>
    <!-- 指标列表 -->
    <IndexList
      :visible.sync="indexListDialog.visible"
      :defaultValues="indexListDialog.defaultValues"
      :selectableCallBack="selectableCallBack"
      :defaultSearch="{
        factoryDeptCode: form.factoryDeptCode,
        workshopId: form.workshopId,
        workshopCode: form.workshopCode,
        lineId: form.lineId,
        metaIndexs: metaIndexSearchOfIndexList,
      }"
      :multiple="true"
      @closeDialog="handleIndexListClose"
    ></IndexList>
    <!-- 设备列表 -->
    <EquipList
      :visible.sync="equipListDialog.visible"
      :defaultValues="equipListDialog.defaultValues"
      :defaultSearch="{
        factoryDeptCode: form.factoryDeptCode,
        workshopId: form.workshopId,
        workshopCode: form.workshopCode,
        lineId: form.lineId,
        sortcode: form.equipSortCode,
      }"
      :multiple="false"
      rowKey="equipId"
      @closeDialog="handleEquipListClose"
    ></EquipList>
  </div>
</template>
<script>
import {
  saveIndexConfig,
  getIndexConfigDetail,
  getIndexConfigCode,
} from "@/api/indexMgmt/configuration";
import { checkPermi } from "@/utils/permission";
import MetaIndexList from "@/views/components/metaIndexList";
import IndexList from "@/views/components/indexList";
import EquipList from "@/views/components/equipList";
import WorkTree from "@/utils/workTree";
export default {
  components: { MetaIndexList, IndexList, EquipList },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  dicts: [
    "sys_yes_no",
    "indexType",
    "indexBizOrgDimension",
    "indexTimeDimension",
    "indexGranularity",
    "indexSubTypeOne_PD",
    "indexSubTypeTwo_ECM",
    "equipSortcode",
    "indexUnit_ED",
    "indexUnit_PD",
    "indexDataGroupBy",
    "indexDataSource",
    "timeUnit",
  ],
  data() {
    return {
      loading: false,
      form: {
        metaIndexId: null,
        metaIndexName: null,
        indexConfigName: null,
        indexConfigCode: null,
        timeDimension: null,
        bizOrgDimension: null,
        factoryDeptId: null,
        factoryDeptCode: null,
        workshopId: null,
        workshopCode: null,
        lineId: null,
        equipSortCode: null,
        equipId: null,
        equipName: null,
        defRelaDtosId: null,
        defRelaDtosName: null,
        configRelaDtos: [],
        configRelaName: null,
        indexGranularity: null,
        indexType: null,
        indexSubTypeOne: null,
        indexSubTypeTwo: null,
        qulityControl: null,
        indexUnit: null,
        remark: null,
        indexDataSource: null,
        sysCalculator: null,
        expression: null,
        calInterval: null,
        calIntervalUnit: null,
        rangePerCal: null,
        latestCalTime: null,
        scadaPointCode: null,
      },
      rules: {
        metaIndexName: [
          { required: true, message: "请选择所属元指标", trigger: "change" },
        ],
        indexConfigName: [
          { required: true, message: "请输入指标名称", trigger: "change" },
        ],
        factoryDeptId: [
          { required: true, message: "请选择工厂", trigger: "change" },
        ],
        // equipName: [
        //   { required: true, message: "请选择所属设备", trigger: "change" },
        // ],
      },
      workTree: null,
      factoryDeptOptions: [],
      workshopOptions: [],
      lineOptions: [],
      // 元指标选择弹框
      indexMetaListDialog: {
        visible: false,
        defaultValues: [],
      },
      // 指标选择弹框
      indexListDialog: {
        visible: false,
        defaultValues: [],
      },
      // 设备选择弹框
      equipListDialog: {
        visible: false,
        defaultValues: [],
      },
      metaSelectableCallBack: (row) => {
        return row.bizOrgDimension != "HD";
      },
      // 关联指标不允许选择自己
      selectableCallBack: (row) => {
        if (!this.row) {
          return true;
        }
        return row.id != this.row.id;
      },
      saveloading: false,
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    canEdit() {
      // 优先组件参数控制
      if (this.disabled == true) {
        return false;
      }
      // 判断是否有编辑权限
      if (this.row?.id) {
        return checkPermi(["indexMgmt:configuration:edit"]);
      }
      return true;
    },
    timeDimensionDictMap() {
      return this.dictToMap(this.dict.indexTimeDimension);
    },
    bizOrgDimensionDictMap() {
      return this.dictToMap(this.dict.indexBizOrgDimension);
    },
    // 指标单位
    // 如果选择的指标类型为设备参数类，下拉选择范围为：indexUnit_ED
    // 如果选择的指标类型为生产绩效类，下拉选择范围为： indexUnit_PD
    indexUnitOption() {
      if (this.form.indexType == "ED") {
        return this.dict.indexUnit_ED;
      }
      return this.dict.indexUnit_PD;
    },
    // 关联指标的筛选条件
    metaIndexSearchOfIndexList() {
      if (!this.form.defRelaDtosId) {
        return null;
      }
      return {
        metaIndexIds: this.form.defRelaDtosId,
        metaIndexNames: this.form.defRelaDtosName,
      };
    },
  },
  created() {},
  methods: {
    handleClose() {
      this.saveloading = false;
      this.resetFormData();
    },
    async handleOpen() {
      this.loading = true;

      // 工厂-车间-产线
      this.workTree = new WorkTree();
      await this.workTree.affterLoad();
      this.factoryDeptOptions = this.workTree.getFactory();

      this.getDetail();
    },
    getDetail() {
      if (!this.row?.id) {
        // 默认获取第一个工厂
        const results = this.getOwnFirstLine();
        this.form.factoryDeptCode = results[0]?.factoryDeptCode || "";
        this.form.factoryDeptId = results[0]?.factoryDeptId || "";
        this.loading = false;
        return;
      }
      this.loading = true;
      getIndexConfigDetail(this.row.id)
        .then((res) => {
          if (res.code == 200 && res.data) {
            const {
              indexMetaDto,
              indexConfigName,
              indexConfigCode,
              factoryDeptId,
              factoryDeptCode,
              workshopId,
              workshopCode,
              lineId,
              equipId,
              equipName,
              configRelaDtos,
              indexDataSource,
              sysCalculator,
              expression,
              calInterval,
              calIntervalUnit,
              rangePerCal,
              latestCalTime,
              scadaPointCode,
            } = res.data;
            this.form = {
              metaIndexId: indexMetaDto?.id || null,
              metaIndexName: indexMetaDto?.indexName || null,
              indexConfigName,
              indexConfigCode,
              timeDimension: indexMetaDto?.timeDimension || null,
              bizOrgDimension: indexMetaDto?.bizOrgDimension || null,
              factoryDeptId,
              factoryDeptCode,
              workshopId,
              workshopCode,
              lineId,
              equipSortCode: indexMetaDto?.equipSortCode || null,
              equipId,
              equipName,
              defRelaDtosId:
                indexMetaDto?.defRelaDtos
                  ?.map((ele) => ele.relaIndexId)
                  .join(",") || null,
              defRelaDtosName:
                indexMetaDto?.defRelaDtos
                  ?.map((ele) => ele.indexMetaDto.indexName)
                  .join(",") || null,
              configRelaDtos:
                configRelaDtos?.map((ele) => ({
                  indexConfigId: ele.indexConfigId,
                  relaIndexConfigId: ele.relaIndexConfigId,
                  relaIndexConfigName: ele.indexConfigDto?.indexConfigName,
                })) || [],
              configRelaName:
                configRelaDtos
                  ?.map((ele) => ele.indexConfigDto.indexConfigName)
                  .join(",") || null,
              indexGranularity: indexMetaDto?.indexGranularity || null,
              indexType: indexMetaDto?.indexType || null,
              indexSubTypeOne: indexMetaDto?.indexSubTypeOne || null,
              indexSubTypeTwo: indexMetaDto?.indexSubTypeTwo || null,
              qulityControl: indexMetaDto?.qulityControl || null,
              indexUnit: indexMetaDto?.indexUnit || null,
              remark: indexMetaDto?.remark || null,
              indexDataSource,
              sysCalculator,
              expression,
              calInterval,
              calIntervalUnit,
              rangePerCal,
              latestCalTime,
              scadaPointCode,
            };
          }
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    handleSubmit() {
      if (!this.canEdit) {
        return;
      }
      this.saveloading = true;
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          const id = this.row?.id || null;
          const {
            metaIndexId,
            indexConfigName,
            indexConfigCode,
            factoryDeptId,
            factoryDeptCode,
            workshopId,
            lineId,
            equipId,
            configRelaDtos,
            remark,
            indexDataSource,
            sysCalculator,
            expression,
            calInterval,
            calIntervalUnit,
            rangePerCal,
            latestCalTime,
            scadaPointCode,
          } = this.form;

          const param = {
            id: this.row?.id,
            indexConfigCode,
            indexConfigName,
            metaIndexId,
            factoryDeptId,
            factoryDeptCode,
            workshopId,
            lineId,
            equipId,
            indexDataSource,
            scadaPointCode,
            sysCalculator,
            expression,
            calInterval,
            calIntervalUnit,
            rangePerCal,
            latestCalTime,
            remark,
            configRelaDtos: configRelaDtos.map(
              ({ indexConfigId, relaIndexConfigId }) => ({
                indexConfigId,
                relaIndexConfigId,
              })
            ),
          };
          saveIndexConfig(param)
            .then((res) => {
              if (res.code == 200) {
                this.msgSuccess(id ? "修改成功！" : "新增成功！");
                this.$emit("submit-success");
                this.dialogVisible = false;
              }
              this.saveloading = false;
            })
            .catch(() => {
              this.saveloading = false;
            });
        } else {
          this.saveloading = false;
        }
      });
    },
    resetFormData() {
      this.form = {
        metaIndexId: null,
        metaIndexName: null,
        indexConfigName: null,
        indexConfigCode: null,
        timeDimension: null,
        bizOrgDimension: null,
        factoryDeptId: null,
        factoryDeptCode: null,
        workshopId: null,
        workshopCode: null,
        lineId: null,
        equipSortCode: null,
        equipId: null,
        equipName: null,
        defRelaDtosId: null,
        defRelaDtosName: null,
        configRelaDtos: [],
        configRelaName: null,
        indexGranularity: null,
        indexType: null,
        indexSubTypeOne: null,
        indexSubTypeTwo: null,
        qulityControl: null,
        indexUnit: null,
        remark: null,
        indexDataSource: null,
        sysCalculator: null,
        expression: null,
        calInterval: null,
        calIntervalUnit: null,
        rangePerCal: null,
        latestCalTime: null,
        scadaPointCode: null,
      };
      this.$refs.ruleForm?.resetFields();
    },
    // 打开所属元指标弹窗
    handleOpenMetaIndexList() {
      const { metaIndexId, metaIndexName } = this.form;
      if (metaIndexId) {
        this.indexMetaListDialog.defaultValues = [
          {
            id: metaIndexId,
            indexName: metaIndexName,
          },
        ];
      } else {
        this.indexMetaListDialog.defaultValues = [];
      }
      this.indexMetaListDialog.visible = true;
    },
    handleMetaIndexListClose(list) {
      if (!list?.length) {
        this.form.metaIndexId = "";
        this.form.metaIndexName = "";
        this.form.equipSortCode = "";
        this.form.defRelaDtosId = "";
        this.form.defRelaDtosName = "";
        this.form.indexGranularity = "";
        this.form.indexType = "";
        this.form.indexSubTypeOne = "";
        this.form.indexSubTypeTwo = "";
        this.form.qulityControl = "";
        this.form.indexUnit = "";
        this.form.remark = "";
        this.form.bizOrgDimension = "";
        this.form.timeDimension = "";
        this.form.workshopId = "";
        this.form.workshopCode = "";
        this.form.lineId = "";
        return;
      }
      this.form.metaIndexId = list[0].id;
      this.form.metaIndexName = list[0].indexName;
      this.form.equipSortCode = list[0].equipSortCode;
      this.form.defRelaDtosId = list[0].defRelaDtos
        ?.map((ele) => ele.relaIndexId)
        .join(",");
      this.form.defRelaDtosName = list[0].defRelaDtos
        ?.map((ele) => ele.indexMetaDto.indexName)
        .join(",");
      this.form.indexGranularity = list[0].indexGranularity;
      this.form.indexType = list[0].indexType;
      this.form.indexSubTypeOne = list[0].indexSubTypeOne;
      this.form.indexSubTypeTwo = list[0].indexSubTypeTwo;
      this.form.qulityControl = list[0].qulityControl;
      this.form.indexUnit = list[0].indexUnit;
      this.form.remark = list[0].remark;
      this.form.bizOrgDimension = list[0].bizOrgDimension;
      this.form.timeDimension = list[0].timeDimension;
      this.form.workshopId = "";
      this.form.workshopCode = "";
      this.form.lineId = "";

      // 生成编码
      this.getIndexConfigCodeByMetaIndex(this.form.metaIndexId);
    },
    // 根据所属元指标，自动获取指标编码
    getIndexConfigCodeByMetaIndex(metaIndexId) {
      if (!metaIndexId) {
        return;
      }
      getIndexConfigCode(metaIndexId).then((res) => {
        this.form.indexConfigCode = res.data || null;
      });
    },
    // 打开关联指标弹窗
    handleOpenIndexList() {
      this.indexListDialog.defaultValues =
        this.form.configRelaDtos?.map((ele) => ({
          id: ele.relaIndexConfigId,
          indexConfigName: ele.relaIndexConfigName,
        })) || [];
      this.indexListDialog.visible = true;
    },
    handleIndexListClose(list) {
      const rowId = this.row?.id || null;
      this.form.configRelaDtos = list.map((ele) => ({
        indexConfigId: rowId,
        relaIndexConfigId: ele.id,
        relaIndexConfigName: ele.indexConfigName,
      }));
      this.form.configRelaName = list
        .map((ele) => ele.indexConfigName)
        .join(",");
    },
    // 具体组织的工厂选择变化
    handleFactoryDeptIdChange(value) {
      if (!value) {
        this.form.factoryDeptCode = null;
        return;
      }
      this.form.factoryDeptCode = this.factoryDeptOptions.find(
        (ele) => ele.factoryDeptId == value
      ).factoryDeptCode;
      // 清空所属指标和关联指标
      this.clearFormByOrg();
      this.form.workshopId = "";
      this.form.workshopCode = "";
      this.form.lineId = "";
    },
    // 具体组织的车间选择变化
    handleWorkshopIdChange(value) {
      if (!value) {
        this.form.workshopCode = null;
        return;
      }
      this.form.workshopCode = this.workshopOptions.find(
        (ele) => ele.workshopId == value
      ).workshopCode;
      // 清空所属指标和关联指标
      this.clearFormByOrg();
      this.form.lineId = "";
    },
    // 清空所属指标和关联指标
    clearFormByOrg() {
      this.form.equipId = "";
      this.form.equipName = "";
      this.form.configRelaDtos = [];
      this.form.configRelaName = "";
    },
    // 打开设备列表
    handleOpenEquipList() {
      const { equipId, equipName } = this.form;
      if (equipId) {
        this.equipListDialog.defaultValues = [
          {
            equipId: equipId,
            equipName,
          },
        ];
      } else {
        this.equipListDialog.defaultValues = [];
      }
      this.equipListDialog.visible = true;
    },
    // 关闭设备列表
    handleEquipListClose(list) {
      if (!list?.length) {
        this.form.equipId = null;
        this.form.equipName = null;
      }
      this.form.equipId = list[0].equipId;
      this.form.equipName = list[0].equipName;
    },
  },
  watch: {
    "form.factoryDeptId": {
      handler(newVal) {
        if (newVal) {
          this.workshopOptions = this.workTree.getWorkshop({
            factoryDeptId: newVal,
          });
        } else {
          this.workshopOptions = [];
        }
      },
    },
    "form.workshopId": {
      handler(newVal) {
        if (newVal) {
          this.lineOptions = this.workTree.getProductionLine({
            workshopId: newVal,
          });
        } else {
          this.lineOptions = [];
        }
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  justify-content: space-between;
  flex-flow: wrap;
  .el-form-item {
    width: 49%;
    &.full-width {
      width: 100%;
    }
  }
}
::v-deep .rule-form {
  .el-form-item__content {
    display: flex;
    align-items: center;
    .system-num {
      white-space: nowrap;
      margin-left: 10px;
    }
    .el-date-editor.el-input,
    .el-select,
    .el-cascader,
    .factory-select {
      width: 100%;
    }
  }
}
.organization {
  display: flex;
  gap: 10px;
}
</style>
